react-router4.0 路由传参跳转及获取参数
路由的跳转,传参分别是通过路由的三个属性history
,location
,match
来进行的,可通过从最上层的路由props传至组件中,也可以通过以下形式获取1
2import {withRouter} from 'react-router-dom'
export default withRouter(Index)
这样Index
组件的props就可以拿到这三个属性了
传参跳转history
params
- 需要现在路由表中配置
1
2
3<Route path="/:id">
```
2. 通过`history.push`进行跳转
history.push(‘/123’); //或者
history.push({pathname: ‘/123’});
1
2
3
43. history 属性中还有一些其他的方法,此处不提。其他文档中都可以查到
### query
1. 通过`history.push`进行跳转
history.push({pathname: ‘/‘, search=”?page=1”});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
## 获取参数
### params `match`
- params 获取参数是通过`match` 获取参数
- `match.params.xxx`
### query `location`
- query 获取参数是通过`location`获取参数
- `location.search`获取到`?page=1`字符串
- `yarn add query-string`
- `queryString.parse(location.search);`
- 就可以将参数转换成对象
还有种跳转是 state
1. 通过`history.push`进行跳转
history.push({pathname: ‘/‘, state={page:1}});`